package com.rover.service.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grid.Page;
import com.rover.dao.BaseDao;
import com.rover.entity.system.Code;
import com.rover.entity.system.CodeValue;

@Service
@Transactional
public class CodeValueService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao<CodeValue> codeValueDao;
	@Autowired
	private BaseDao<Code> codeDao;

	@Transactional(readOnly = true)
	public Page<CodeValue> query(Page<CodeValue> page, String strWhere, Map<String, Object> params) {
		String strTable = "select  new CodeValue(cv.id,cv.itemText,cv.itemValue,cv.description,cv.sequence,cv.treeCode)  from CodeValue cv left join cv.code  " + strWhere;
		strTable += " order by sequence";
	
		String totalHql = "select count(cv) from CodeValue cv left join cv.code "+strWhere;
		page.setTotalCount(codeValueDao.count(totalHql,params));
		List<CodeValue> li=codeValueDao.find(strTable,params, page.getPageNo(),
				page.getPageSize());
		
		page.setResult(li);
		return page;
	}
	

	@Transactional
	public void save(CodeValue codeValue,String codeId) {
		if(codeValue.getCode()==null){
			codeValue.setCode(codeDao.get(Code.class,Long.valueOf(codeId)));
		}
		
		codeValueDao.saveOrUpdate(codeValue);
	}
	/*
	 * 编码树添加
	 * */
	@Transactional
	public void treeSave(CodeValue codeValue,String codeId) {
			codeValue.setCode(codeDao.get(Code.class,Long.valueOf(codeId)));
			codeValue.setTreeCode(getNextCode(codeValue.getpTreeCode()));
			CodeValue pCodeValue=null;
			List<CodeValue> li=codeValueDao.find("from CodeValue cv where cv.treeCode=? and cv.code.id=?",codeValue.getpTreeCode(),Long.valueOf(codeId));
			if(li.size()>0){
				pCodeValue=li.get(0);
			}
			codeValue.setpCodeValue(pCodeValue);
		codeValueDao.save(codeValue);
	}
	@Transactional
	public void treeUpdate(CodeValue codeValue,String codeId) throws Exception {
		
		CodeValue oldCodeValue=codeValueDao.get(CodeValue.class, codeValue.getId());
		oldCodeValue.setDescription(codeValue.getDescription());
		oldCodeValue.setItemText(codeValue.getItemText());
		oldCodeValue.setItemValue(codeValue.getItemValue());
		oldCodeValue.setSequence(codeValue.getSequence());
		String oldCode=oldCodeValue.getTreeCode();
	    String	oldPCode=oldCodeValue.getTreeCode();
		if(oldPCode == null || oldPCode.equals("")){
			oldPCode="";
		}
		else
		{
			oldPCode=oldPCode.substring(0,oldPCode.length()-3);
		}
		if(!oldPCode.equals(codeValue.getpTreeCode())){
			
		    String strNewTreeCode=getNextCode(codeValue.getpTreeCode());
		    if(strNewTreeCode.startsWith(oldCode))
		    	throw new Exception("保存失败，原因是父节点不能变成它的子节点的节点！");
		    CodeValue pCodeValue=null;
		    //判断父节点是否是顶级节点
		   if(!codeValue.getpTreeCode().equals(""))
			   pCodeValue=codeValueDao.find("from CodeValue cv where cv.treeCode=?",codeValue.getpTreeCode()).get(0);
		    oldCodeValue.setpCodeValue(pCodeValue);
		    oldCodeValue.setTreeCode(strNewTreeCode);
			List<CodeValue> li=codeValueDao.find("from CodeValue cv where cv.treeCode like '"+oldCode+"%' and cv.id<>? and cv.code.id=?",codeValue.getId(),Long.valueOf(codeId));
            for(CodeValue cv:li){
            	
            	codeValueDao.executeHql("update CodeValue cv set cv.treeCode='"+strNewTreeCode+cv.getTreeCode().substring(oldCode.length())+"' where cv.id="+cv.getId().toString());
            }
		}
		
		
		codeValueDao.update( oldCodeValue);
	}
	@Transactional
	public void delete(Long id) {
		codeValueDao.delete(CodeValue.class,id);
	}
	
	/*
	 * 根据codeID获取对应的值列表
	 * @codeID  code表里的id
	 * */
	@Transactional(readOnly = true)
	public List<CodeValue> getCodeValue(Long codeID) {
	return	codeValueDao.find("select new CodeValue(cv.id,cv.itemText,cv.itemValue) from CodeValue cv join cv.code where cv.code.id="+codeID.toString());
	}
	/*
	 * 根据code名称获取对应的值列表
	 * @codeName  code表里的name
	 * */
	@Transactional(readOnly = true)
	public List<CodeValue> getCodeValue(String codeName) {
	return	codeValueDao.find("select new CodeValue(cv.id,cv.itemText,cv.itemValue) from CodeValue cv join cv.code where cv.code.name=?",codeName.toString());
	}
	/*
     * 获取treeCode的数据源
     * */
	@Transactional(readOnly = true)
    public List<CodeValue> getTreeList(String codeName){
		return	codeValueDao.find("select cv from CodeValue cv join cv.code where codeValue.pCodeValue is null and cv.code.name=?",codeName.toString());
	}
    /*
     * 获取treeCode的数据源
     * */
	@Transactional(readOnly = true)
    public List<CodeValue> getTreeList(Long codeID){
		return	codeValueDao.find("select cv from CodeValue cv join cv.code where cv.pCodeValue is null and cv.code.id="+codeID.toString());
	}
	
	 /// <summary>
    /// 取得下一个部门的编号
    /// </summary>
    /// <param name="con"></param>
    /// <param name="ParentDeptCode"></param>
    /// <returns></returns>
    private String getNextCode(String parentTreeCode)
    {
        String SQL = "select max(substring(treeCode,(length(treeCode)-3+1),3)) from CodeValue where 1=1  ";

        if (parentTreeCode == "")
        {
            SQL += " and length(treeCode)=3 ";
        }
        else
        {
            SQL += " and length(treeCode)=" + (parentTreeCode.length() + 3) + " and substring(treeCode,1," + parentTreeCode.length()+ ")='" + parentTreeCode + "' ";
        }
        Object MaxID = codeValueDao.getCurrentSession().createQuery(SQL).uniqueResult();
        
        if (MaxID == null)
        {
            if (parentTreeCode == "")
                return "001";
            else
                return parentTreeCode + "001";
        }
        else
        {
            if (parentTreeCode == "")
                return String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
            else
                return parentTreeCode + String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
        }

    }
	/*
	 * 添加的时候判断名称是否重复
	 * @name 要判断的名称
	 * */
	public Boolean isItemTextRepeat(CodeValue codeValue,Long codeId){
		String hql="select count(id) from CodeValue cv where cv.itemText=:itemText and cv.code.id=:codeId";
		 Map<String, Object> params=new HashMap<String, Object>();
		 params.put("itemText", codeValue.getItemText());
		 params.put("codeId", codeId);
		 if(codeValue.getId()!=null){
			 hql+=" and id<>:id";
			 params.put("id", codeValue.getId());
		 }
		 
		if(codeValueDao.count(hql, params)>0){
			return true;
		}
		else
			return false;
	}
	/*
	 * 添加的时候判断名称是否重复
	 * @name 要判断的名称
	 * */
	public Boolean isItemValueRepeat(CodeValue codeValue,Long codeId){
		String hql="select count(id) from CodeValue cv where cv.itemValue=:itemValue and cv.code.id=:codeId";
		 Map<String, Object> params=new HashMap<String, Object>();
		 params.put("itemValue", codeValue.getItemValue());
		 params.put("codeId", codeId);
		 if(codeValue.getId()!=null){
			 hql+=" and id<>:id";
			 params.put("id", codeValue.getId());
		 }
		if(codeValueDao.count(hql, params)>0){
			return true;
		}
		else
			return false;
	}

}
